/**
 *====================================================
 * 文件名称: UserActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月23日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.user.action.v1;

import java.util.Date;
import java.util.List;

import com.starchain.smsender.SendMsgUtil;
import com.yuexunit.account.action.v2.AccountActionApi;
import com.yuexunit.account.action.v2.model.AccountAlias;
import com.yuexunit.account.action.v2.model.AccountId;
import com.yuexunit.account.action.v2.model.AccountNameType;
import com.yuexunit.core.BusinessException;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.common.util.StringUtils;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.AuthenticodeEntity;
import com.yuexunit.finance.member.entity.FingerTrunkAccountMappingEntity;
import com.yuexunit.finance.member.entity.LogisticsClerkEntity;
import com.yuexunit.finance.member.entity.lexicon.AuthenticodeEnum;
import com.yuexunit.finance.member.service.AuthenticodeService;
import com.yuexunit.finance.member.service.FingerTrunkAccountMappingService;
import com.yuexunit.finance.member.service.LogisticsClerkService;
import com.yuexunit.finance.project.entity.AccountTerminalEntity;
import com.yuexunit.finance.project.entity.FinanceEmployeeEntity;
import com.yuexunit.finance.project.service.AccountTerminalService;
import com.yuexunit.finance.project.service.FinanceEmployeeService;
import com.yuexunit.finance.system.action.v1.dto.EmployeeRoleInfoCasotr;
import com.yuexunit.finance.user.action.v1.model.CurrentUserInfo;
import com.yuexunit.finance.user.action.v1.model.EmployeeRoleInfo;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.permission.action.PermissionActionsApi;
import com.yuexunit.permission.action.dto.RoleListDto;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.tenant.TenantActionApi;
import com.yuexunit.util.StringUtil;
import com.yuexunit.util.UuidUtil;

/**
 * @ClassName: UserActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月23日 下午9:38:45
 */
@Implements(UserActionApi.class)
public class UserActionApiImpl implements UserActionApi {

	private AccountTerminalService accountTerminalService = ComponentFactory.loadClass(AccountTerminalService.class);

	private AuthenticodeService authenticodeService = ComponentFactory.loadClass(AuthenticodeService.class);

	private AccountActionApi accountAction = ComponentFactory.loadClass(AccountActionApi.class);

	private TenantActionApi tenantAction = ComponentFactory.loadClass(TenantActionApi.class);

	private LogisticsClerkService logisticsClerkService = ComponentFactory.loadClass(LogisticsClerkService.class);

	private PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);

	private FinanceEmployeeService financeEmployeeService = ComponentFactory.loadClass(FinanceEmployeeService.class);
	
	private FingerTrunkAccountMappingService fingerTrunkAccountMappingService = ComponentFactory.loadClass(FingerTrunkAccountMappingService.class);

	private String getAuthenticodeUuid(String mobile, AuthenticodeEnum type) {
		AuthenticodeEntity persistence = authenticodeService.inquireAuthenticodeDetail(mobile);
		String authenticodeUuid = UuidUtil.randomUUID();
		String authenticode = StringUtils.getIdentifyingCode();
		if (persistence == null) {
			AuthenticodeEntity entity = new AuthenticodeEntity();
			entity.setMobile(mobile);
			entity.setAuthType(type);
			entity.setAuthenticode(authenticode);
			entity.setAuthenticodeUuid(authenticodeUuid);
			entity.setEffectiveDateTime(DateUtils.addHours(new Date(), 1));
			authenticodeService.createAuthenticode(entity);
		} else {
			persistence.setAuthType(type);
			persistence.setAuthenticode(authenticode);
			persistence.setAuthenticodeUuid(authenticodeUuid);
			persistence.setEffectiveDateTime(DateUtils.addHours(new Date(), 1));
			authenticodeService.persistAuthenticode(persistence);
		}
		String message = authenticode;
		if (AuthenticodeEnum.REGISTER == type) {
			// 注册帐号
			AccountId account = accountAction.inquireAccountIdByAlias(mobile, AccountNameType.MOBILE.ordinal());
			if (account != null) {
				throw new BusinessException("该手机号已被注册");
			}
			message = "账号申请验证码:" + authenticode;
		} else if (AuthenticodeEnum.FOGET_PASSWORD == type) {
			message = "账号找回密码,您的验证码:" + authenticode;
		} else if (AuthenticodeEnum.SEAL_SUBMIT_CHECK == type) {
			message = "印章提交审核,您的验证码:" + authenticode + ",如非本人操作，请忽略本短信。";
		} else if (AuthenticodeEnum.CHANGE_MOBILE == type) {
			// 注册帐号
			AccountId account = accountAction.inquireAccountIdByAlias(mobile, AccountNameType.MOBILE.ordinal());
			if (account != null) {
				throw new BusinessException("该手机号已被注册");
			}
			message = "账号修改手机号,您的验证码:" + authenticode;
		}
		try {
//			SmsSendUtil.sendSMS("指尖金融", mobile, message);
			SendMsgUtil.sendMsg(mobile, message);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return authenticodeUuid;
	}

	private void validateAuthenticode(String mobile, String authenticode, String authenticodeUuid, boolean clean) {
		AuthenticodeEntity persistence = authenticodeService.inquireAuthenticodeDetail(mobile);
		if (persistence == null) {
			throw new BusinessException("该验证码不存在!");
		}
		if (!persistence.getAuthenticode().equals(authenticode)) {
			throw new BusinessException("验证码不匹配!");
		}
		if (!persistence.getAuthenticodeUuid().equals(authenticodeUuid)) {
			throw new BusinessException("校验码不匹配!");
		}
		if (persistence.getEffectiveDateTime().before(new Date())) {
			throw new BusinessException("验证码已过期!");
		}
		if (clean) {
			authenticodeService.deleteAuthenticode(persistence.getAuthenticodeId());
		}
	}

	@Override
	public String registerEnterpriseAccount(String mobile) {
		return getAuthenticodeUuid(mobile, AuthenticodeEnum.REGISTER);
	}

	@Override
	@Transactional
	public void validateEnterpriseRegisterUuid(String mobile, String authenticode, String registerUuid) {
		// 注册帐号
		AccountId account = accountAction.inquireAccountIdByAlias(mobile, AccountNameType.MOBILE.ordinal());
		if (account != null) {
			throw new BusinessException("该手机号已被注册");
		}
		validateAuthenticode(mobile, authenticode, registerUuid, false);
	}

	@Override
	@Transactional
	public void registerEnterprisePassword(String mobile, String authenticode, String registerUuid, String password, String userId) {
		validateAuthenticode(mobile, authenticode, registerUuid, true);
		// 注册帐号
		AccountId account = accountAction.inquireAccountIdByAlias(mobile, AccountNameType.MOBILE.ordinal());
		if (account != null) {
			throw new BusinessException("该手机号已被注册");
		}
		Long accountId = accountAction.createAccountSimple(mobile, password);
		AccountAlias accountAlias = new AccountAlias();
		accountAlias.setAccountId(accountId);
		accountAlias.setAccountName(mobile);
		accountAlias.setType(AccountNameType.MOBILE);
		accountAction.updateAccountAlias(accountAlias);

		// 创建租户信息
		tenantAction.createTenantByAccountId(accountId, null);
		
		if (StringUtil.isNotBlank(userId)) {
			FingerTrunkAccountMappingEntity ftame = fingerTrunkAccountMappingService.inquireFingerTrunkAccountMappingDetail(userId);
			if (ftame != null) {
				throw new BusinessException("该用户已存在！");
			} else {
				ftame = new FingerTrunkAccountMappingEntity();
			}
			ftame.setFinanceAccountId(accountId);
			ftame.setFingerTrunkAccountId(userId);
			fingerTrunkAccountMappingService.createFingerTrunkAccountMapping(ftame);
		}
	}

	@Override
	public String retrieveEnterprisePassword(String mobile) {
		// 注册帐号
		AccountId account = accountAction.inquireAccountIdByAlias(mobile, AccountNameType.MOBILE.ordinal());
		if (account == null) {
			throw new BusinessException("该手机号还未注册");
		}
		return getAuthenticodeUuid(mobile, AuthenticodeEnum.FOGET_PASSWORD);
	}

	@Override
	@Transactional
	public void validateEnterpriseChangePasswordUuid(String mobile, String authenticode, String retrievePasswordUuid) {
		validateAuthenticode(mobile, authenticode, retrievePasswordUuid, false);
	}

	@Override
	@Transactional
	public void retrieveLogisticsResetPasswordUuid(Long clerkId) {
		LogisticsClerkEntity logisticsClerkEntity = logisticsClerkService.inqueryLogisticsClerkDetail(clerkId);
		if (logisticsClerkEntity == null) {
			throw new BusinessException("找不到此物流公司人员");
		}
		// 设置密码
		AccountId accountId = accountAction.inquireAccountIdByAlias(logisticsClerkEntity.getClerkMobile(), AccountNameType.MOBILE.ordinal());
		if (accountId == null) {
			throw new BusinessException("手机号还未注册");
		}
		accountAction.resetPassword(accountId.getAccountId(), "123456");
	}

	@Override
	@Transactional
	public void retrieveEnterpriseResetPasswordUuid(String mobile, String password, String authenticode, String retrievePasswordUuid) {
		validateAuthenticode(mobile, authenticode, retrievePasswordUuid, true);
		// 设置密码
		AccountId accountId = accountAction.inquireAccountIdByAlias(mobile, AccountNameType.MOBILE.ordinal());
		if (accountId == null) {
			throw new BusinessException("手机号还未注册");
		}
		accountAction.resetPassword(accountId.getAccountId(), password);
	}

	@Override
	public void validateAccountPassword(String password) {
		accountAction.changePassword(FinanceSessionContext.getAccountId(), password, password);
	}

	@Override
	public String changeEnterpriseAccountNewMobile(String password, String mobile) {
		accountAction.changePassword(FinanceSessionContext.getAccountId(), password, password);
		return getAuthenticodeUuid(mobile, AuthenticodeEnum.CHANGE_MOBILE);
	}

	@Override
	@Transactional
	public void validateEnterpriseChangeMobileUuid(String password, String mobile, String authenticode, String changeMobileUuid) {
		validateAuthenticode(mobile, authenticode, changeMobileUuid, true);
		accountAction.changePassword(FinanceSessionContext.getAccountId(), password, password);
		AccountAlias accountAlias = new AccountAlias();
		accountAlias.setAccountId(FinanceSessionContext.getAccountId());
		accountAlias.setAccountName(mobile);
		accountAlias.setType(AccountNameType.MOBILE);
		accountAction.updateAccountAlias(accountAlias);
	}

	@Override
	public CurrentUserInfo inquireCurrentUserInfo() {
		CurrentUserInfo userInfo = new CurrentUserInfo();
		userInfo.setFullName(FinanceSessionContext.getAccountFullName());
		return userInfo;
	}

	@Override
	public void updateEmployeeRole(Long employeeId, List<Long> roleIds) {
		FinanceEmployeeEntity employee = financeEmployeeService.inquireEmployee(employeeId);
		permissionAction.updateAccountRole(employee.getAccountId(), roleIds);
	}

	@Override
	public List<EmployeeRoleInfo> inquireEmployeeRoleList(Long employeeId) {
		FinanceEmployeeEntity employee = financeEmployeeService.inquireEmployee(employeeId);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(employee.getAccountId());
		return EmployeeRoleInfoCasotr.toEmployeeRoleInfoList(rl);
	}

	@Override
	@Transactional
	public void registerTerminalAccount(String terminalSerial) {
		AccountTerminalEntity entity = accountTerminalService.inquireAccountTerminal(FinanceSessionContext.getAccountId());
		if (entity == null) {
			entity = new AccountTerminalEntity();
			entity.setAccountId(FinanceSessionContext.getAccountId());
			entity.setTerminalSerial(terminalSerial);
			accountTerminalService.createAccountTerminal(entity);
		} else {
			entity.setTerminalSerial(terminalSerial);
			accountTerminalService.updateAccountTerminal(entity);
		}
	}

	@Override
	public Integer existUser(String userId) {
		FingerTrunkAccountMappingEntity ftame = fingerTrunkAccountMappingService.inquireFingerTrunkAccountMappingDetail(userId);
		if (ftame == null) {
			return 0;
		} else {
			return 1;
		}
	}

	@Override
	public String sealSubmitCheckInfo(String mobile) {
		// 注册帐号
		return getAuthenticodeUuid(mobile, AuthenticodeEnum.SEAL_SUBMIT_CHECK);
	}

	@Override
	public void validateSealSubmitCheckInfo(String mobile, String checkUuid,
			String authenticode) {
		validateAuthenticode(mobile, authenticode, checkUuid, false);
	}
}
